<?php

class MaterialWarehouseInboundController extends Controller {
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	//public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array(
				'allow',
				// allow all users to perform 'index' and 'view' actions
				'actions' => array(
					'index',
					'indexStatistic',
					'view',
					'searchHistory',
					'dynamicLoadItems',
					'checkExistToken'
				),
				'roles' => array(
					'materialWarehouseInboundView'
				),
			),
			array(
				'allow',
				// allow admin user to perform 'admin' and 'delete' actions
				'actions' => array(
					'create',
					'update',
					'admin',
					'delete',
					'updateItems',
					'deleteItem',
					'dynamicAddRequisitionItems',
				),
				'roles' => array(
					'materialWarehouseInboundManage'
				),
			),
			array(
				'deny',
				// deny all users
				'users' => array(
					'*'
				),
			),
		);
	}

	public function actions() {
		return array(
			'updateItems' => array(
				'class' => 'web.controllers.materialWarehouseInbound.UpdateMaterialWarehouseInboundItemsAction',
			),
			'dynamicAddRequisitionItems' => array(
				'class' => 'web.controllers.materialWarehouseInbound.DynamicAddWarehouseInboundItemFromRequisitionAction',
			),
			'dynamicLoadItems' => array(
				'class' => 'web.controllers.materialWarehouseInbound.DynamicLoadMaterialWarehouseInboundItemsAction',
			),
			'checkExistToken' => array(
				'class' => 'web.controllers.materialWarehouseInbound.DynamicCheckExistMaterialWarehouseInboundTokenAction',
			),
		);
	}
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id) {
		$this->render('view', array(
			'model' => $this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate() {
		$model = new MaterialWarehouseInbound;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['MaterialWarehouseInbound'])) {
			$model->attributes = $_POST['MaterialWarehouseInbound'];
			if ($model->save())
				$this->redirect(array(
					'view',
					'id' => $model->id
				));
		}

		$this->render('create', array(
			'model' => $model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id) {
		$model = $this->loadModel($id);

		if (!$model->isRecent && !Yii::app()->user->checkAccess('admin')) {
			throw new CHttpException(400, '一周之前创建的记录不可编辑');
		}
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['MaterialWarehouseInbound'])) {
			$model->attributes = $_POST['MaterialWarehouseInbound'];
			if ($model->save())
				$this->redirect(array(
						'view',
						'id' => $model->id
					));
		}

		$this->render('update', array(
				'model' => $model,
			));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id) {
		if (Yii::app()->request->isPostRequest) {
			// we only allow deletion via POST request
			$model = $this->loadModel($id);

			if (!$model->isRecent && !Yii::app()->user->checkAccess('admin')) {
				throw new CHttpException(400, '一周之前创建的记录不可编辑');
			}
			$model->delete();
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if (!isset($_GET['ajax']))
				$this
					->redirect(
						isset($_POST['returnUrl']) ? $_POST['returnUrl']
							: array(
								'admin'
							));
		} else
			throw new CHttpException(400,
				'Invalid request. Please do not repeat this request again.');
	}

	public function actionDeleteItem($id) {
		if (Yii::app()->request->isPostRequest) {
			// we only allow deletion via POST request
			$item = MaterialWarehouseInboundItem::model()->findByPk($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if (!isset($_GET['ajax']))
				$this
					->redirect(
						isset($_POST['returnUrl']) ? $_POST['returnUrl']
							: array(
								'admin'
							));
		} else
			throw new CHttpException(400,
				'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex() {
		$searchModel = new MaterialWarehouseInboundSearch();
		$searchModel->unsetAttributes(); // clear any default values
		if (isset($_GET['MaterialWarehouseInboundSearch'])) {
			$searchModel->attributes = $_GET['MaterialWarehouseInboundSearch'];
		}
		$dataProvider = new CActiveDataProvider('MaterialWarehouseInbound',
			array(
				'criteria' => $searchModel->createCriteria()
			));
		$this
			->render('index',
				array(
					'dataProvider' => $dataProvider,
					'searchModel' => $searchModel
				));
	}

	public function actionIndexStatistic() {
		$searchModel = new MaterialWarehouseInboundSearch();
		if (isset($_POST['MaterialWarehouseInboundSearch'])) {
			$searchModel->attributes = $_POST['MaterialWarehouseInboundSearch'];
		}
		if (!$searchModel->materialModelId) {
			return;
		}
		$model = MaterialWarehouseInbound::model();
		$criteria = $searchModel->createCriteria(true);
		$criteria->select = 'sum(amountStandardUnit) as totalAmount, materialModel.unit as unit
			                ';
		$criteria->join = 'LEFT JOIN {{material_warehouse_inbound_item}} as item on materialWarehouseInboundId='
			. $model->getTableAlias() . '.id'
			. ' LEFT JOIN {{material_model}} as materialModel on materialModelId=materialModel.id';
		$commandBuilder = Yii::app()->db->getSchema()->getCommandBuilder();
		$command = $commandBuilder->createFindCommand($model->getTableSchema(), $criteria);
		$row = $command->queryRow();

		$formatter = Yii::app()->format;
		$result = array(
			'totalAmount' => $formatter->formatAmount($row['totalAmount']) . ' ' . $row['unit'],
		);

		JHtml::jsonHeader();
		echo CJSON::encode($result);
	}
	/**
	 * Manages all models.
	 */
	public function actionAdmin() {
		$model = new MaterialWarehouseInbound('search');
		$model->unsetAttributes(); // clear any default values
		if (isset($_GET['MaterialWarehouseInbound']))
			$model->attributes = $_GET['MaterialWarehouseInbound'];

		$this->render('admin', array(
				'model' => $model,
			));
	}

	public function actionSearchHistory($id = null, $materialModelId = null, $date = null,
		$projectId = null) {
		if ($id) {
			$model = $this->loadModel($id);
			JHTML::jsonHeader();
			$history = MaterialManager::getMaterialWarehouseInboundHistory($materialModelId,
				$model->projectId, $model->submitDate, $model->id);
			$lastItemText = MaterialManager::getMaterialWarehouseInboundLast($materialModelId,
				$model->projectId, $model->submitDate, $model->id);
			echo CJSON::encode(array(
				'history' => $history,
				'last' => $lastItemText
			));
		} elseif ($date && $projectId) {
			$history = MaterialManager::getMaterialWarehouseInboundHistory($materialModelId,
				$projectId, $date);
			$lastItemText = MaterialManager::getMaterialWarehouseInboundLast($materialModelId,
				$projectId, $date);
			echo CJSON::encode(
				array(
					'history' => $history,
					'last' => $lastItemText
				));
		}
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id) {
		$model = MaterialWarehouseInbound::model()->findByPk($id);
		if ($model === null)
			throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model) {
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'material-warehouse-inbound-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
